// 网络系统
class NetworkSystem {
    constructor(world) {
        this.world = world;
        this.socket = null;
        this.lastUpdateTime = 0;
        this.lastInputTime = 0; // 初始化lastInputTime
        this.updateInterval = 1000 / 60; // 60fps
        
        // 状态插值相关属性
        this.previousState = null; // 上一次接收到的游戏状态
        this.currentState = null;  // 当前接收到的游戏状态
        this.interpolationFactor = 0; // 插值因子
        this.networkUpdateRate = 1000 / 20; // 服务器以20fps的速率发送更新
    }

    // 初始化网络系统
    init(socket) {
        this.socket = socket;

        // 监听服务器事件
        this.socket.on('connect', () => {
            console.log('已连接到服务器');
            // 检查是否处于等待状态
            const waitingMessage = document.getElementById('waitingMessage');
            if (waitingMessage && waitingMessage.style.display === 'block') {
                // 如果在等待界面，直接返回房间列表
                window.location.href = '/rooms.html';
                return;
            }
        });

        this.socket.on('disconnect', () => {
            console.log('与服务器断开连接');
        });

        this.socket.on('error', (error) => {
            console.error('网络错误:', error);
            // 检查是否是房间不存在的错误
            if (error.message === '房间不存在') {
                window.location.href = '/rooms.html';
            }
        });

        // 监听游戏状态更新
        this.socket.on('gameState', (gameState) => {
            // 保存上一个状态用于插值
            this.previousState = this.currentState;
            this.currentState = gameState;
            
            // 如果是第一次收到状态，直接更新
            if (!this.previousState) {
                this.world.updateGameState(gameState);
            }
            
            // 重置插值因子
            this.interpolationFactor = 0;
            
            // 记录接收时间
            this.lastUpdateTime = Date.now();
        });

        // 监听玩家加入
        this.socket.on('playerJoined', (data) => {
            console.log(`玩家 ${data.playerId} 加入了游戏`);
        });

        // 监听玩家离开
        this.socket.on('playerLeft', (data) => {
            console.log(`玩家 ${data.playerId} 离开了游戏`);
        });

        // 监听游戏开始
        this.socket.on('gameStart', () => {
            console.log('游戏开始');
            document.getElementById('waitingMessage').style.display = 'none';
        });

        // 监听游戏结束
        this.socket.on('gameOver', ({ winnerId }) => {
            console.log(`游戏结束，获胜者: ${winnerId}`);
            if (winnerId === this.world.localPlayerId) {
                document.getElementById('victoryDialog').style.display = 'block';
                
                // 移除之前可能存在的事件监听器
                const returnButton = document.getElementById('returnToRoomList');
                returnButton.replaceWith(returnButton.cloneNode(true));
                
                // 重新获取新的按钮元素
                const newReturnButton = document.getElementById('returnToRoomList');
                
                // 添加返回房间列表按钮的点击事件
                newReturnButton.addEventListener('click', () => {
                    console.log('获胜玩家点击了返回按钮');
                    // 通知服务器玩家离开房间
                    this.socket.emit('leaveRoom', { roomId: document.getElementById('roomId').textContent });
                    document.getElementById('victoryDialog').style.display = 'none';
                    window.location.href = '/rooms.html';
                });
            }
        });

        // 监听被击败
        this.socket.on('defeated', () => {
            console.log('你被击败了');
            this.world.emit('defeated');
            const defeatedDialog = document.getElementById('defeatedDialog');
            defeatedDialog.style.display = 'block';
            
            // 移除之前可能存在的事件监听器
            const returnButton = document.getElementById('returnToRoomListDefeated');
            returnButton.replaceWith(returnButton.cloneNode(true));
            
            // 重新获取新的按钮元素
            const newReturnButton = document.getElementById('returnToRoomListDefeated');
            
            // 添加返回房间列表按钮的点击事件
            newReturnButton.addEventListener('click', () => {
                console.log('玩家点击了返回按钮');
                // 通知服务器玩家离开房间
                this.socket.emit('leaveRoom', { roomId: document.getElementById('roomId').textContent });
                defeatedDialog.style.display = 'none';
                window.location.href = '/rooms.html';
            });
        });
    }

    // 更新系统
    update(deltaTime) {
        if (!this.socket) return;
        
        const currentTime = Date.now();
        
        // 发送玩家输入到服务器
        if (this.world.localInput && currentTime - this.lastInputTime >= this.updateInterval) {
            this.socket.emit('playerInput', this.world.localInput);
            this.lastInputTime = currentTime;
        }
        
        // 执行状态插值
        this.interpolateGameState(deltaTime);
    }
    
    // 状态插值方法
    interpolateGameState(deltaTime) {
        // 如果没有两个状态可以插值，直接返回
        if (!this.previousState || !this.currentState) return;
        
        // 计算插值因子 (0到1之间)
        const timeSinceUpdate = Date.now() - this.lastUpdateTime;
        this.interpolationFactor = Math.min(timeSinceUpdate / this.networkUpdateRate, 1);
        
        // 创建插值后的游戏状态
        const interpolatedState = {
            tanks: {},
            bullets: {},
            walls: this.currentState.walls, // 墙壁通常不需要插值
            timestamp: Date.now()
        };
        
        // 对坦克进行插值
        for (const tankId in this.currentState.tanks) {
            const currentTank = this.currentState.tanks[tankId];
            
            // 如果坦克在前一个状态中不存在，直接使用当前状态
            if (!this.previousState.tanks || !this.previousState.tanks[tankId]) {
                interpolatedState.tanks[tankId] = {...currentTank};
                continue;
            }
            
            const previousTank = this.previousState.tanks[tankId];
            interpolatedState.tanks[tankId] = {
                ...currentTank,
                x: previousTank.x + (currentTank.x - previousTank.x) * this.interpolationFactor,
                y: previousTank.y + (currentTank.y - previousTank.y) * this.interpolationFactor
            };
        }
        
        // 对子弹进行插值
        for (const bulletId in this.currentState.bullets) {
            const currentBullet = this.currentState.bullets[bulletId];
            
            // 如果子弹在前一个状态中不存在，直接使用当前状态
            if (!this.previousState.bullets || !this.previousState.bullets[bulletId]) {
                interpolatedState.bullets[bulletId] = {...currentBullet};
                continue;
            }
            
            const previousBullet = this.previousState.bullets[bulletId];
            interpolatedState.bullets[bulletId] = {
                ...currentBullet,
                x: previousBullet.x + (currentBullet.x - previousBullet.x) * this.interpolationFactor,
                y: previousBullet.y + (currentBullet.y - previousBullet.y) * this.interpolationFactor
            };
        }
        
        // 更新游戏世界状态
        this.world.updateGameState(interpolatedState);
    }

    // 发送开火事件
    sendFire(bulletData) {
        if (this.socket) {
            this.socket.emit('playerFire', bulletData);
        }
    }

    // 发送击中事件
    sendHit(hitData) {
        if (this.socket) {
            this.socket.emit('playerHit', hitData);
        }
    }
}

// 如果在浏览器环境中，将NetworkSystem添加到window对象
if (typeof window !== 'undefined') {
    window.NetworkSystem = NetworkSystem;
}

// 如果在Node.js环境中，导出NetworkSystem类
if (typeof module !== 'undefined' && module.exports) {
    module.exports = NetworkSystem;
}